# coding: utf-8
import datetime

import httpx
import pandas
import peewee
from apscheduler.schedulers.blocking import BlockingScheduler


url = "http://fxapi.jsxych.com/dbDeviceHistory/add"
db_data = peewee.MySQLDatabase("miaofu", user="mf", passwd="mf888888", host="127.0.0.1", port=3306)
SITE = {}


class Device(peewee.Model):
    device_id = peewee.CharField(primary_key=True)
    device_name = peewee.CharField()
    device_code = peewee.CharField()
    data_time = peewee.DateTimeField()
    uptime = peewee.DateTimeField()
    is_use = peewee.IntegerField()
    total_rain_flow = peewee.CharField()
    rain_flow = peewee.CharField()
    water_level = peewee.CharField()
    up_water_level = peewee.CharField()
    low_water_level = peewee.CharField()

    class Meta:
        database = db_data
        table_name = "xl_device"


class Data(peewee.Model):
    report_time = peewee.CharField()
    read_time = peewee.DateTimeField()
    water_level = peewee.CharField()
    up_water_level = peewee.CharField()
    low_water_level = peewee.CharField()
    rain_flow = peewee.CharField()
    total_rain_flow = peewee.CharField()
    v = peewee.CharField()

    class Meta:
        database = db_data

    @classmethod
    def set_table_name(cls, table_name):
        cls._meta.table_name = table_name


def load_site():
    df = pandas.read_excel("site.xlsx", sheet_name="Sheet1", header=1)
    df = df[["站点编号", "站点名称"]]
    df.columns = ["code", "name"]
    for _, row in df.iterrows():
        SITE[row["name"]] = row["code"]


def post_data():
    data = []
    with db_data.connection_context():
        for item in Device.select():
            if item.device_name is None or item.is_use == 0:
                continue
            item.site_code = SITE.get(item.device_name)
            data.append({
                "reportTime": item.data_time.strftime("%Y-%m-%d %H:%M:%S"),
                "readTime": item.data_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rainData": item.rain_flow,
                "waterData": item.water_level,
                "upLevel": item.up_water_level,
                "lowLevel": item.low_water_level,
                "totalRainData": item.total_rain_flow,
                "flowInfo": "N/A",
                "voltage": "12.1",
                "siteCode": item.site_code,
            })
            print(f" - {item.device_name} ({item.site_code}) {item.water_level} {item.up_water_level} {item.low_water_level}")
    now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{now_str}] Total {len(data)} records.")
    try:
        response = httpx.post(url, json=data, timeout=5).json()
    except Exception as e:
        response = str(e)
    print(f"[{now_str}] {response}")


def read_data(device_code: str):
    Data.set_table_name(f"data_realtime_hz_{device_code}")
    if not Data.table_exists():
        return None
    return Data.select().order_by(Data.read_time.desc()).get()


if __name__ == "__main__":
    load_site()
    post_data()
    scheduler = BlockingScheduler()
    scheduler.add_job(post_data, 'interval', minutes=5)
    scheduler.start()
